package cn.net.isir.dao;

import cn.net.isir.controller.manager.CommissionController;
import cn.net.isir.entity.*;
import cn.net.isir.utils.DateUtils;
import org.aspectj.weaver.patterns.OrSignaturePattern;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author liuxubo
 * @filename MyCommissionDao.java
 * @package cn.net.isir.dao
 * @email lxb@isir.net.cn
 * @date 2019/03/21
 * @comment
 * @since 1.8
 */
@Repository
public class MyCommissionDao {
    @Resource
    protected SqlSessionTemplate sqlSessionTemplate;
    @Resource
    private MinipIndexDataDao minipIndexDataDao;
    @Resource
    private OrderDao orderDao;

    protected String getMinipNamespace() {
        return MinipIndexDataDao.class.getName();
    }

    /**
     * 获取首页数据
     *
     * @param salesmanId    用户ID
     * @param turnedShopIds 已转出店铺ID
     * @param timeRangeList 有效时间列表
     * @return 首页数据
     */
    public Map<String, BigDecimal> getIndexData(String salesmanId, String turnedShopIds, List<TimeRange> timeRangeList, Factor factor, List<Medals> medalsList) {
        Map<String, Object> map = new HashMap<>();
        map.put("salesmanId", salesmanId);
        map.put("turnedShpIds", turnedShopIds);
        // 所有未转出店铺列表
        List<Shop> shops = sqlSessionTemplate.selectList(getMinipNamespace() + ".noTurnShopList", map);
        map.clear();
        map.put("salesmanId", salesmanId);
        map.put("turnedShpIds", turnedShopIds);
        map.put("timeRangeList", timeRangeList);
        // 所有可转出店铺列表
        List<Shop> shopIds = sqlSessionTemplate.selectList(getMinipNamespace() + ".CanTurnShops", map);
       if ((shops == null || shops.size() == 0) && (shopIds == null || shopIds.size() == 0)) {
            Map<String, BigDecimal> resultMap = new HashMap<>();
            resultMap.put("monthFlow", BigDecimal.ZERO);
            resultMap.put("monthTurn", BigDecimal.ZERO);
            resultMap.put("totalAmount", BigDecimal.ZERO);
            return resultMap;
        }

        // 计算所有店铺的流水佣金
        BigDecimal allShopFlow = minipIndexDataDao.queryMonthFlow(salesmanId, turnedShopIds, timeRangeList);
        // 本月流水佣金
        BigDecimal rollBefore = factor.getRollBefore().multiply(new BigDecimal("0.01"));
        BigDecimal flowFee = allShopFlow.multiply(rollBefore).setScale(3,BigDecimal.ROUND_HALF_UP);
        // 本月结转佣金
        BigDecimal turnFee = BigDecimal.ZERO;

        // 计算转出佣金
        Calendar calendar = Calendar.getInstance();
        int maxDate = calendar.getActualMaximum(Calendar.DATE);
        String startTime = new SimpleDateFormat("yyyy-MM-## 00:00:00").format(calendar.getTime());
        String endTime = new SimpleDateFormat("yyyy-MM-## 23:59:59").format(calendar.getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       if(shopIds != null && shopIds.size() != 0){
            // 每个可转出店铺
           for (Shop shopId : shopIds){
               int dayLiveCount = 0;
               BigDecimal monthTotalTurn = BigDecimal.ZERO;
               // 获取每一天的数据
               for (int i2 = 1; i2 <= maxDate; i2++) {

                   String dateStr = String.valueOf(i2);
                   if (i2 < 10) {
                       dateStr = "0" + dateStr;
                   }
                   String realStime = startTime.replace("##", dateStr);
                   String realEtime = endTime.replace("##", dateStr);
                   try {
                       Date sDate = sdf.parse(realStime);
                       Date eDate = sdf.parse(realEtime);
                       Order order = new Order();
                       order.setShopId(shopId.getId());
                       order.setQueryStartOrderTime(sDate);
                       order.setQueryEndOrderTime(eDate);

                       List<Order> orderList = orderDao.selectList(order);

                       // 每日订单列表
                       int dayLiveOrderCount = 0;
                       BigDecimal dayTotalTurn = BigDecimal.ZERO;
                       for (Order order1 : orderList) {
                           dayTotalTurn = dayTotalTurn.add(order1.getFinalTotal());
                           if (dayLiveOrderCount >= 20) {
                               dayLiveCount++;
                               break;
                           }
                           if (order1.getFinalTotal().compareTo(new BigDecimal(8.0D)) > 0) {
                               dayLiveOrderCount++;
                           }
                       }
                       // 如果未达到日活,则佣金不算
                       if (dayLiveOrderCount < 20) {
                           dayTotalTurn = BigDecimal.ZERO;
                       }
                       // 增加每天的流水佣金
                       monthTotalTurn = monthTotalTurn.add(dayTotalTurn);
                       // 仅计算22天的数据
                       if (dayLiveCount >= 22) {
                           break;
                       }
                   } catch (ParseException e) {
                       e.printStackTrace();
                   }
               }
               turnFee = turnFee.add(monthTotalTurn);
           }
       }

        BigDecimal c = BigDecimal.ZERO;

        for (Medals medals : medalsList) {
            if (medals.getMin().multiply(new BigDecimal("10000")).compareTo(turnFee) < 0 && medals.getMax().multiply(new BigDecimal("10000")).compareTo(turnFee) > 0) {
                c = medals.getFactor();
            }
        }

        BigDecimal rollOut = factor.getRollOut().multiply(new BigDecimal("0.01"));
        turnFee = turnFee.multiply(rollOut).multiply(c).setScale(3,BigDecimal.ROUND_HALF_UP);

        Map<String, BigDecimal> resultMap = new HashMap<>();
        resultMap.put("monthFlow", flowFee);
        resultMap.put("monthTurn", turnFee);
        resultMap.put("totalAmount", turnFee.add(flowFee));
        return resultMap;
    }

    /**
     * 获取不可转出店铺列表
     *
     * @param salesmanId    销售人员ID
     * @param turnedShopIds 已转出店铺
     * @param timeRangeList 销售人员有效范围
     * @return 不可转出店铺列表
     */
    public List<Map<String, Object>> getCannotTurnShopList(String salesmanId, String turnedShopIds, Factor factor, List<TimeRange> timeRangeList) {
        Map<String, Object> map = new HashMap<>();
        map.put("salesmanId", salesmanId);
        map.put("turnedShpIds", turnedShopIds);
        // 所有未转出店铺列表
        List<Shop> shops = sqlSessionTemplate.selectList(getMinipNamespace() + ".noTurnShopList", map);
        map.clear();
        map.put("salesmanId", salesmanId);
        map.put("turnedShpIds", turnedShopIds);
        map.put("timeRangeList", timeRangeList);
        // 所有可转出店铺列表
        List<Shop> shopIds = sqlSessionTemplate.selectList(getMinipNamespace() + ".CanTurnShops", map);

        List<Shop> cannotTurnShopList = new ArrayList<>();
        for (Shop shop : shops) {
            boolean isExist = false;
            if(shopIds!=null && !shopIds.isEmpty()){
                for (Shop shopId : shopIds) {
                    if (shopId.getId().equals(shop.getId())) {
                        isExist = true;
                    }
                }
            }
            if (!isExist) {
                cannotTurnShopList.add(shop);
            }
        }

        List<Map<String, Object>> list = new ArrayList<>();
        for (Shop shop : cannotTurnShopList) {
            Map<String, Object> oneShop = new HashMap<>();
            oneShop.put("shopName", shop.getName());
            BigDecimal rollBefore = factor.getRollBefore().multiply(new BigDecimal("0.01"));
            BigDecimal monthFlow = minipIndexDataDao.queryShopIntervalFlow(timeRangeList, shop.getId(),
                    DateUtils.getCurrentMonthStartTime(), DateUtils.getCurrentMonthEndTime()).multiply(rollBefore).setScale(3,BigDecimal.ROUND_HALF_UP);
            oneShop.put("monthFlow", monthFlow);
            oneShop.put("createTime", shop.getCreateTime());
            list.add(oneShop);
        }
        return list;
    }

    /**
     * 可结转店铺列表
     *
     * @param salesmanId    销售人员ID
     * @param turnedShopIds 已转出店铺
     * @param timeRangeList 销售人员有效范围
     * @return 可转出店铺列表
     */
    public List<Map<String, Object>> getCanTurnShopList(String salesmanId, String turnedShopIds, Factor factor, List<TimeRange> timeRangeList) {
        Map<String, Object> map = new HashMap<>();
        map.put("salesmanId", salesmanId);
        map.put("turnedShpIds", turnedShopIds);
        // 所有未转出店铺列表
        List<Shop> shops = sqlSessionTemplate.selectList(getMinipNamespace() + ".noTurnShopList", map);
        map.clear();
        map.put("salesmanId", salesmanId);
        map.put("turnedShpIds", turnedShopIds);
        map.put("timeRangeList", timeRangeList);
        // 所有可转出店铺列表
        List<Shop> shopIds = sqlSessionTemplate.selectList(getMinipNamespace() + ".CanTurnShops", map);

        List<Shop> canTurnShopList = new ArrayList<>();
        for (Shop shop : shops) {
            boolean isExist = false;
            if(shopIds!=null && !shopIds.isEmpty()){
                for (Shop shopId : shopIds) {
                    if (shopId.getId().equals(shop.getId())) {
                        isExist = true;
                    }
                }
            }
            if (isExist) {
                canTurnShopList.add(shop);
            }
        }

        if (canTurnShopList.size() == 0) {
            return new ArrayList<>();
        }

        // 计算转出佣金
        Calendar calendar = Calendar.getInstance();
        int maxDate = calendar.getActualMaximum(Calendar.DATE);
        String startTime = new SimpleDateFormat("yyyy-MM-## 00:00:00").format(calendar.getTime());
        String endTime = new SimpleDateFormat("yyyy-MM-## 23:59:59").format(calendar.getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 计算每个店铺
        List<Map<String, Object>> list = new ArrayList<>();
        for (Shop shop : canTurnShopList) {
            Map<String, Object> oneShop = new HashMap<>();
            oneShop.put("shopName", shop.getName());
            BigDecimal rollBefore = factor.getRollBefore().multiply(new BigDecimal("0.01"));
            BigDecimal monthFlow = minipIndexDataDao.queryShopIntervalFlow(timeRangeList, shop.getId(),
                    DateUtils.getCurrentMonthStartTime(), DateUtils.getCurrentMonthEndTime()).multiply(rollBefore)
                    .setScale(3,BigDecimal.ROUND_HALF_UP);
            oneShop.put("monthFlow",monthFlow);
            oneShop.put("createTime", shop.getCreateTime());


            // 转结佣金
            BigDecimal turnFee = BigDecimal.ZERO;

            String shopId = shop.getId();

            int dayLiveCount = 0;
            BigDecimal monthTotalTurn = BigDecimal.ZERO;
            // 获取每一天的数据
            for (int i2 = 1; i2 <= maxDate; i2++) {

                String dateStr = String.valueOf(i2);
                if (i2 < 10) {
                    dateStr = "0" + dateStr;
                }
                String realStime = startTime.replace("##", dateStr);
                String realEtime = endTime.replace("##", dateStr);
                try {
                    Date sDate = sdf.parse(realStime);
                    Date eDate = sdf.parse(realEtime);
                    Order order = new Order();
                    order.setShopId(shopId);
                    order.setQueryStartOrderTime(sDate);
                    order.setQueryEndOrderTime(eDate);

                    List<Order> orderList = orderDao.selectList(order);

                    // 每日订单列表
                    int dayLiveOrderCount = 0;
                    BigDecimal dayTotalTurn = BigDecimal.ZERO;
                    for (Order order1 : orderList) {
                        dayTotalTurn = dayTotalTurn.add(order1.getFinalTotal());
                        if (dayLiveOrderCount >= 20) {
                            dayLiveCount++;
                            break;
                        }
                        if (order1.getFinalTotal().compareTo(new BigDecimal(8.0D)) > 0) {
                            dayLiveOrderCount++;
                        }
                    }
                    // 如果未达到日活,则佣金不算
                    if (dayLiveOrderCount < 20) {
                        dayTotalTurn = BigDecimal.ZERO;
                    }
                    // 增加每天的流水佣金
                    monthTotalTurn = monthTotalTurn.add(dayTotalTurn);
                    // 仅计算22天的数据
                    if (dayLiveCount >= 22) {
                        break;
                    }

                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            turnFee = turnFee.add(monthTotalTurn).setScale(3,BigDecimal.ROUND_HALF_UP);
            oneShop.put("monthTurn", turnFee);
            list.add(oneShop);
        }
        return list;
    }
}
